package cn.edu.laud.sany.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

public class MyLog
{
	private boolean console;
	private FileWriter fWriter;
	private String threadName;
	
	private static final DateFormat DATE_FORMAT = DateFormat.getInstance();
	
	public static MyLog getMyLog(String fileName, boolean enableConsole)
	{
		MyLog log = new MyLog();
		log.console = enableConsole;
		log.threadName = "";
		File file = new File(fileName);
		if (file.exists() == false)
		{
			try
			{
				file.createNewFile();
			}
			catch (IOException e)
			{
				e.printStackTrace();
				return null;
			}
		}
		try
		{
			log.fWriter = new FileWriter(file, true);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return null;
		}
		return log;
	}
	
	public void setThreadName(String name)
	{
		if (name == null)
		{
			return;
		}
		threadName = "[" + name + "]";
	}
	
	public static String getNowTimeString()
	{
		Date now = new Date();
		return (DATE_FORMAT.format(now));
	}
	
	public String getLogWithTime(String log)
	{
		Date now = new Date();
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		sb.append(DATE_FORMAT.format(now));
		sb.append("]");
		sb.append(threadName);
		sb.append(" ");
		sb.append(log);
		return sb.toString();
	}
	
	public synchronized void printLog(String log)
	{
		String printLogString = getLogWithTime(log);
		if (console)
		{
			System.out.println(printLogString);
		}
		try
		{
			fWriter.write(printLogString);
			fWriter.write("\r\n");
			fWriter.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public synchronized void printLogError(String log)
	{
		String printLogString = getLogWithTime(log);
		if (console)
		{
			System.err.println(printLogString);
		}
		try
		{
			fWriter.write(printLogString);
			fWriter.write("\r\n");
			fWriter.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public void info(String log)
	{
		printLog(log);
	}
	
	public void debug(String log)
	{
		printLog(log);
	}
	
	public void warn(String log)
	{
		printLog(log);
	}
	
	public void error(String log)
	{
		printLogError(log);
	}
	
}
